package com.cgt.xiaotao.order.handler;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.alibaba.fastjson.JSON;

@MappedTypes(List.class)
@MappedJdbcTypes(JdbcType.OTHER)
public class LongListJsonTypeHandler extends BaseTypeHandler<List<Long>> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, List<Long> parameter, JdbcType jdbcType) throws SQLException {
        if (parameter != null) {
            String json = JSON.toJSONString(parameter);
            ps.setString(i, json);
        } else {
            ps.setString(i, "[]");
        }
    }

    @Override
    public List<Long> getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String json = rs.getString(columnName);
        return parseJsonToList(json);
    }

    @Override
    public List<Long> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String json = rs.getString(columnIndex);
        return parseJsonToList(json);
    }

    @Override
    public List<Long> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String json = cs.getString(columnIndex);
        return parseJsonToList(json);
    }

    private List<Long> parseJsonToList(String json) {
        if (StringUtils.isBlank(json) || "null".equals(json)) {
            return new ArrayList<>();
        }
        try {
            json = json.trim();
            if (json.startsWith("\"") && json.endsWith("\"")) {
                // 处理可能被转义的JSON字符串
                json = json.substring(1, json.length() - 1).replace("\\\"", "\"");
            }
            return JSON.parseArray(json, Long.class);
        } catch (Exception e) {
            e.printStackTrace();
            return new ArrayList<>();
        }
    }
}
